<template>
  <div class="cartContainer">
    <!-- 有设置收货地址 -->
    <div v-if="cartGoodslist.length > 0" class="addressWrap">
      <div v-if="hasAddress" class="address">
        <van-icon name="location-o" />
        <div class="info" @click="$router.push('/address')">
          <div>{{ address.name }} / {{ address.tel }} 邮编: {{ address.postalCode }}</div>
          <div>{{ address.province }}{{ address.city }}{{ address.country }}{{ address.addressDetail }}</div>
        </div>
      </div>
      <!-- 无设置收货地址 -->
      <van-button v-else block type="info" plain @click="$router.push('/addaddress')">添加地址</van-button>
    </div>

    <div class="cartlist">
      <div class="item" v-for="(item, index) in cartGoodslist" :key="item.id">
        <van-checkbox @click="checkBoxChange(item.id, $store.getters.getGoodsStatusById[item.id])"
          v-model="$store.getters.getGoodsStatusById[item.id]" icon-size="24px" checked-color="#ee0a24" />
        <div class="imgWrap">
          <img :src="item.thumb_path">
        </div>
        <div class="info">
          <div class="title">{{ item.title }}</div>
          <div class="area">
            <div class="price">&yen;{{ item.sell_price }}</div>
            <van-stepper @change="numberChange($event, item.id)" v-model="$store.getters.getGoodsNumberById[item.id]"
              theme="round" button-size="22" disable-input />
            <van-button type="danger" @click="delCartGoods(item.id, index)">删除</van-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 没有购物车商品时展示 -->
    <div class="emptyCar" v-if="cartGoodslist.length === 0">
      <van-empty class="custom-image" :image="emptyCar" description="你的购物车空空如也">
        <van-button @click="$router.replace('/home/index')" type="danger" class="bottom-button">去首页</van-button>
      </van-empty>
    </div>
    <!-- 订单支付 -->
    <van-submit-bar class="mb50" :price="$store.getters.getTotalPrice * 100" button-text="提交订单"
      :disabled="cartGoodslist.length === 0 || !hasAddress || !$store.getters.getCarSelectedGoodsIds" @submit="onSubmit">
      <template #tip>仅支持微信支付</template>
      <template #default>共选中 {{ $store.getters.getCarSelectedTotalNumber }} 件</template>
    </van-submit-bar>
  </div>
</template>

<script>
import { fetchCartGoods } from "../api/index";
import { fetchGetUserAddress } from "../api/address";
import { genOrderId } from "../util/tools.js";
import { fetchCommitOrder } from "../api/order.js";
import emptyCar from "../assets/image/car.png"
export default {
  data() {
    return {
      emptyCar,
      cartGoodslist: [],
      ids: this.$store.getters.getCarGoodsIds,
      address: {},
      hasAddress: false,
    };
  },
  created() {
    this._fetchCartGoods();
    this._fetchUserAddress();
  },
  methods: {
    async _fetchCartGoods() {
      //购物车没有商品则不请求
      if (!this.ids) {
        return;
      }
      let { message } = await fetchCartGoods(this.ids);
      this.cartGoodslist = message;
    },
    async _fetchUserAddress() {
      // 购物车没有商品则不请求
      if (!this.ids) {
        return;
      }
    //   let user_id = this.$store.state.userInfo.id;
    //   // 判断是否登录 方案1：这里判断token 方案2：导航守卫中判断
    //   if (!user_id) {
    //     this.$dialog.alert({
    //       message: '请先登录哦',
    //     }).then(() => {
    //       // on close
    //       this.$router.replace('/login')
    //     });
    //     return;
    //   }
    //   let userAddressAll = await fetchGetUserAddress(user_id);
    //   // 判断是否有地址
    //   this.hasAddress = !!userAddressAll.length;
    //   // 如果用户只有一个收货地址，则就是默认的收货地址
    //   if (!this.hasAddress) {
    //     this.$dialog({ message: '请先完善收货地址' });
    //     return;
    //   }
    //   if (userAddressAll.length === 1) {
    //     this.address = userAddressAll[0];
    //     return;
    //   }
    //   // 判断是否默认收货地址
    //   let defaultIndex = userAddressAll.findIndex(item => item.isDefault === 1);
    //   if (defaultIndex !== -1) {
    //     // 找到了默认地址
    //     this.address = userAddressAll[defaultIndex];
    //   } else {
    //     // 若没有默认地址，则取第一个作为默认地址
    //     this.address = userAddressAll[0];
    //   }
    },
    async onSubmit() {
      let user_id = this.$store.state.userInfo.id;
      if (!user_id) {
        this.$router.push("/login");
        return;
      }
      // 准备好下订单的数据
      let orderData = {
        user_id,
        order_id: genOrderId(),
        address_id: this.address.id,
        total_price: this.$store.getters.getTotalPrice,
        number: this.$store.getters.getCarSelectedTotalNumber,
        goods_ids: this.$store.getters.getCarSelectedGoodsIds
      };
      // 提交订单loading提示
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: "提交订单中",
        forbidClick: true,
        overlay: true
      });
      // 提交订单接口
      let { message, status } = await fetchCommitOrder(orderData);
      this.$toast(message);

      // 关闭上面的提示
      if (status == 0) {
        // 下单成功要清购物车，并跳转到订单列表
        this.$store.commit("clearCartData");
        this.$router.replace("/orderlist");
      }

      this.$toast.clear();
    },
    // 删除商品
    delCartGoods(id, index) {
      // 删除当前data中的商品
      this.cartGoodslist.splice(index, 1);
      // 还要删除vuex
      this.$store.commit("delCartGoods", id);
      console.log(id, index);
    },
    // 切换选中不选中
    checkBoxChange(id, selected) {
      console.log(id, selected);
      this.$store.commit("setGoodsSeleceted", { id, selected });
    },
    numberChange(number, id) {
      this.$store.commit("setGoodsNumber", { number, id });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../assets/scss/var.scss";

.cartContainer {
  height: 100vh;
  background-color: $bgColor;
  padding: 6px;

  .addressWrap {
    .address {
      display: flex;
      align-items: center;
      padding: 4px 10px;
      background-color: #fff;
      border-radius: 6px;
      margin: 6px 0;

      .van-icon {
        margin-right: 20px;
        color: red;
        font-size: 20px;
      }
    }
  }

  .cartlist {
    .item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 4px;
      background-color: #fff;
      border-radius: 6px;
      margin: 6px 0;

      .imgWrap {
        width: 50px;
        height: 50px;
        padding: 4px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .info {
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .title {
          width: 70vw;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }

        .area {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .price {
            color: #ff424a;
          }
        }
      }
    }
  }

  .mb50 {
    margin-bottom: 50px;
  }
}
</style>
